<template>
  <base-load-page :loadState="false" class="base-load-page">
    <template #head>
      <div style="padding-bottom: 15px" class="head-box">
        <div class="left-box">
          <bubble-select-local
            v-model="filterData.productType"
            labelKey="label"
            valueKey="value"
            :filterable="false"
            style="width: 100%"
            :list="[
              { label: '全部商品', value: '' },
              { label: '充值K币', value: 1 },
              { label: '充值VIP', value: 2 },
              { label: '解锁短剧', value: 4 },
            ]"
            placeholder="请选择商品类型"
            @change="getAxiosData(true)"
          ></bubble-select-local>
          <base-input-search
            v-model="filterData.productName"
            clearable
            placeholder="请输入商品名称"
            style="width: 100%"
            maxlength="30"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
        </div>
        <div class="right-box">
          <el-button type="success" :icon="IconPlus" :loading="addLoading" :disabled="addLoading" @click="handleAdd()">新增</el-button>
        </div>
      </div>
    </template>
    <el-table v-loading="baseData.loading" border height="100%" :data="tableData" showOverflowTooltip stripe style="width: 100%">
      <template #empty>
        <base-empty :description="description" :pageLoadButton="[{ text: '重新加载', callBack: () => getAxiosData() }]"></base-empty>
      </template>
      <el-table-column
        fixed
        type="index"
        :index="(index: number) => (filterData.current - 1) * filterData.size + index + 1"
        label="编号"
        sortable
        width="60"
        align="center"
        headerAlign="center"
      ></el-table-column>
      <el-table-column fixed label="商品名称" prop="productName" minWidth="180"></el-table-column>
      <el-table-column label="商品价格(元)" prop="productPrice" minWidth="120"></el-table-column>
      <el-table-column label="商品数量" prop="productQuantity" minWidth="100"></el-table-column>
      <el-table-column label="数量单位" prop="unit" minWidth="90"></el-table-column>
      <el-table-column label="商品类型" prop="productTypeDesc" minWidth="90">
        <template #default="{ row }">
          <el-tag v-if="row.productType === 1" key="el-tag-1" type="success" size="small">{{ row.productTypeDesc }}</el-tag>
          <el-tag v-else-if="row.productType === 2" key="el-tag-2" type="danger" size="small">{{ row.productTypeDesc }}</el-tag>
          <el-tag v-else-if="row.productType === 4" key="el-tag-3" type="primary" size="small">{{ row.productTypeDesc }}</el-tag>
          <el-tag v-else key="el-tag-4" type="warning" size="small">{{ row.productTypeDesc }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="200" align="center" headerAlign="center">
        <template #default="{ row }">
          <el-button link type="danger" size="small" :icon="IconDelete" @click="handleDel(row.productGiveId)">删除商品</el-button>
          <el-button link type="primary" size="small" :loading="row._editLoading" :disabled="row._editLoading" :icon="IconEdit" @click="openEdit(row)">
            编辑商品
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <template #foot>
      <div class="pagination-box">
        <el-pagination
          v-model:currentPage="filterData.current"
          v-model:pageSize="filterData.size"
          :pageSizes="[20, 30, 40, 50]"
          :disabled="baseData.loading"
          :pagerCount="13"
          layout="total, prev, pager, next, sizes, jumper"
          :total="baseData.total"
          @change="getAxiosData(true)"
        ></el-pagination>
      </div>
    </template>
    <!-- 新增商品 -->
    <add-edit-product ref="addEditProductRef"></add-edit-product>
  </base-load-page>
</template>

<script setup lang="ts">
  import IconDelete from '~icons/ep/delete';
  import IconEdit from '~icons/ep/edit';
  import IconSearch from '~icons/ep/search';
  import IconPlus from '~icons/ep/plus';
  import { type GiveProduct, type GiveProductListRequest, delGiveProductAxios, getGiveProductListAxios } from '@/api/product-management';
  import AddEditProduct from './components/add-edit-product.vue';

  type $GiveProduct = GiveProduct & {
    /** 编辑的加载状态 */
    _editLoading?: boolean;
  };
  const baseData = shallowReactive({
    /** 加载状态 */
    loading: true,
    /** 总数量 */
    total: 0,
  });
  const appStore = useAppStore();
  const addEditProductRef = ref<InstanceType<typeof AddEditProduct>>();
  const filterData = ref<GiveProductListRequest>({
    productName: '',
    productType: undefined,
    current: 1,
    size: 40,
  });
  const addLoading = ref();
  const tableData: Ref<$GiveProduct[]> = ref([]);
  const description = ref('');
  onMounted(() => {
    getAxiosData();
  });

  /**
   * 设置表格数据
   */
  async function getAxiosData(showLoading = true) {
    try {
      await nextTick();
      baseData.loading = Boolean(showLoading);
      const res = await getGiveProductListAxios(filterData.value);

      res.data.records.forEach((item) => {
        item._editLoading = false;
      });
      tableData.value = res.data.records;
      description.value = '暂无数据';
      filterData.value.current = res.data.current;
      filterData.value.size = res.data.size;
      baseData.total = res.data.total;
      baseData.loading = false;
    } catch (error) {
      baseData.loading = false;
      tableData.value = [];
      description.value = error.msg || '加载失败，-BD001';
    }
  }

  /**
   * 编辑
   */
  async function openEdit(row: $GiveProduct) {
    try {
      row._editLoading = true;
      const res = await appStore.getProductPriceInfo();
      row._editLoading = false;
      addEditProductRef.value?.show({
        priceInfo: res,
        action: 'edit',
        giveProduct: row,
        editCallBack() {
          getAxiosData();
        },
      });
    } catch (error) {
      row._editLoading = false;
      ElToast.error(error.msg || '获取数据失败，-BD002');
    }
  }

  /** 新增商品 */
  async function handleAdd() {
    try {
      addLoading.value = true;
      const res = await appStore.getProductPriceInfo();
      addLoading.value = false;
      addEditProductRef.value?.show({
        priceInfo: res,
        action: 'add',
        addCallBack() {
          getAxiosData();
        },
      });
    } catch (error) {
      addLoading.value = false;
      ElToast.error(error.msg || '获取数据失败，-BD002');
    }
  }

  /**
   * 删除
   */
  function handleDel(productGiveId: number) {
    ElMessageBox.confirm('删除后不可恢复，您确定删除吗？', '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true,
      beforeClose: async (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true;
          try {
            await delGiveProductAxios(productGiveId);
            await getAxiosData();
            instance.confirmButtonLoading = false;
            done();
            ElToast.success('删除成功');
          } catch (error) {
            instance.confirmButtonLoading = false;
            ElToast.error(error.msg || '删除失败，-BD004');
          }
        } else {
          done();
        }
      },
    });
  }
</script>

<style lang="scss" scoped>
  .pagination-box {
    @include flex(row, nowrap, center, center, center);
    padding-top: 15px;
  }

  .head-box {
    @include flex(row, nowrap, flex-start, center, center);

    .left-box {
      display: grid;
      flex: 1;
      grid-template-columns: repeat(auto-fill, minmax(210px, 1fr));
      grid-gap: 15px;
      margin-right: 15px;
    }
  }
</style>
